<template lang="pug">
  view
    view.addr(@tap="selectAddress")
      view.icon
        image(src="http://120.55.49.138/ShopMall/static/img/addricon.png"  mode)
      view.right
        view.tel-name
          view.name {{ recinfo.name }}
          view.tel {{ recinfo.tel }}
        view.addres {{ recinfo.address.region.label }}          {{ recinfo.address.detailed }}
    view.buy-list
      view.row(v-for="(row,index) in buylist"  :key="index")
        view.goods-info
          view.img
            image(:src="row.img")
          view.info
            view.title {{ row.name }}
            view.spec 选择{{ row.spec }}
            view.price-number
              view.price ￥{{ row.price * row.number }}
              view.number(style="color:red") ×{{ row.number }}
    view.order
      view.row
      view.row
        view.left 备注 :
        view.right
          input(placeholder="选填,备注内容"  v-model="note")
    view.detail
      view.row
        view.nominal 商品金额
        view.content ￥{{ goodsPrice|toFixed }}
    view.blck
    view.footer
      view.settlement
        view.sum 合计:
          view.money ￥{{ sumPrice|toFixed }}
        view.btn(@tap="toPay") 提交订单
</template>

<script>
import provinceData from '../user/address/city-data/province.js';
import cityData from '../user/address/city-data/city.js';
import areaData from '../user/address/city-data/area.js';

export default {
  data() {
    return {
      //session
      sessionid: '',
      hearder: '',
      standby: 0,
      buylist: [],		//订单列表
      skus: [],
      quantitys: [],
      goodsPrice: 0.0,	//商品合计价格
      sumPrice: 0.0,	//用户付款价格
      freight: 0,	//运费
      note: '',		//备注
      int: 0,		//抵扣积分
      deduction: 0,	//抵扣价格
      recinfo: {
        id: 1,
        name: "请选择地址",
        head: "大",
        tel: "",
        address: {region: {"label": "广东省-深圳市-福田区", "value": [18, 2, 1], "cityCode": "440304"}, detailed: ''},
        isDefault: true
      },


//session
      pickerValue: [0, 0, 0],
      provinceDataList: [],
      cityDataList: [],
      areaDataList: [],
      isSelect: false,
      addressList: [],
    };
  },
  onShow() {
    this.provinceDataList = provinceData;
    this.cityDataList = cityData;
    this.areaDataList = areaData;
    this.addressList = [];
    var data = {};
    this.sessionid = uni.getStorageSync("sessionid");
    this.hearder = uni.getStorageSync("hearder");
    console.log('sessionid' + this.sessionid);
    console.log('hearder' + this.hearder);
    if (this.sessionid == null || this.sessionid == '') {
      //uni.showToast({title: "请先登录！"});
      uni.navigateTo({
        url: '../login/login'
      })
      return;
    }
    var header = this.hearder;
    var sessionid = this.sessionid;
    console.log(header + '' + sessionid);

    uni.getStorage({

      key: 'selectAddress',
      success: (e) => {
        console.log('selectAddress');
        this.recinfo = e.data;
        uni.removeStorage({
          key: 'selectAddress'
        })
      }
    });

    if (this.recinfo.id == 1)
      this.$Request.get(this.$api.member.listAddress, data, this.hearder + ' ' + this.sessionid).then(res => {

        if (res.code == 200) {
          let array = res.data;
          for (var i = 0; i < array.length; i++) {
            var addressdata = array[i];
            console.log(i, array[i]);

            var indexprovince = -1;
            var labelprovince = '';
            for (var iprovince = 0; iprovince < this.provinceDataList.length; iprovince++) {
              var item = this.provinceDataList[iprovince];
              if (item.value == addressdata.province) {
                labelprovince = item.label;
                indexprovince = iprovince;
                break;
              }
            }
            console.log("province:" + indexprovince + labelprovince);
            var indexCity = -1;
            var labelCity = '';
            var cityarray = this.cityDataList[indexprovince];
            for (var iCity = 0; iCity < cityarray.length; iCity++) {
              var item = cityarray[iCity];
              if (item.value == addressdata.city) {
                labelCity = item.label;
                indexCity = iCity;
                break;
              }
            }

            console.log("city:" + indexCity + labelCity);
            var indexArea = -1;
            var labelArea = '';
            var areaarray = this.areaDataList[indexprovince][indexCity];
            for (var iArea = 0; iArea < areaarray.length; iArea++) {
              var item = areaarray[iArea];
              if (item.value == addressdata.region) {
                labelArea = item.label;
                indexArea = iArea;
                break;
              }
            }
            console.log("area:" + indexArea + labelArea);
            var address =
                {
                  id: addressdata.id,
                  memberId: addressdata.memberId,
                  name: addressdata.name,
                  head: addressdata.name.substr(0, 1),
                  tel: addressdata.phoneNumber,
                  address: {
                    region:
                        {
                          "label": labelprovince + "-" + labelCity + "-" + labelArea,
                          "value": [indexprovince, indexCity, indexArea],
                          "cityCode": addressdata.region,
                        },
                    detailed: addressdata.detailAddress
                  },
                  isDefault: addressdata.defaultStatus == 0 ? false : true,
                };
            console.log(address.isDefault);
            if (address.isDefault) {
              this.recinfo = address;
              break;
            }
          }
        } else {
          uni.showToast({title: "查询地址失败"});
        }
      });

    //页面显示时，加载订单信息
    uni.getStorage({
      key: 'buylist',
      success: (ret) => {
        this.buylist = ret.data;
        this.goodsPrice = 0;
        //合计
        let len = this.buylist.length;
        console.log(this.buylist);
        for (let i = 0; i < len; i++) {
          this.skus[i] = this.buylist[i].sku;
          this.quantitys[i] = this.buylist[i].number;
          this.goodsPrice = this.goodsPrice + (this.buylist[i].number * this.buylist[i].price);
        }
        this.deduction = 0;
        this.sumPrice = 0;
        this.sumPrice = (parseFloat(this.goodsPrice) - parseFloat(this.deduction) + parseFloat(this.freight)).toFixed(2);
      }
    });

  },
  onHide() {

  },
  onBackPress() {
    //页面后退时候，清除订单信息
    this.clearOrder();
  },
  onLoad(option) {

    console.log(option.standby); //打印出上个页面传递的参数。
    this.standby = option.standby;
  },
  filters: {
    toFixed: function (x) {
      return parseFloat(x).toFixed(2);
    }
  },
  methods: {
    clearOrder() {
      uni.removeStorage({
        key: 'buylist',
        success: (res) => {
          this.buylist = [];
          console.log('remove buylist success');
        }
      });
    },
    toPay() {
      //商品列表
      let paymentOrder = [];
      let goodsid = [];
      let len = this.buylist.length;
      for (let i = 0; i < len; i++) {
        paymentOrder.push(this.buylist[i]);
        goodsid.push(this.buylist[i].id);
      }
      if (paymentOrder.length == 0) {
        uni.showToast({title: '订单信息有误，请重新购买', icon: 'none'});
        return;
      }
      //本地模拟订单提交UI效果
      // uni.showLoading({
      // 	title:'正在提交订单...'
      // })
      this.sessionid = uni.getStorageSync("sessionid");
      this.hearder = uni.getStorageSync("hearder");
      if (this.sessionid == null || this.sessionid == '') {
        uni.showToast({title: "请先登录！"});
        return;
      }

      var data = {
        //"couponid":0,
        "memberReceiveAddressId": this.recinfo.id,
        "payType": 0,
        "useIntegration": 0,

      };

      var header = this.hearder;
      var sessionid = this.sessionid;
      var url = this.$api.order.generateOrder;
      if (this.standby == 1) {
        url = this.$api.order.generateFlashOrderSimple;
        data.skuCode = this.skus[0];
        data.quantity = this.quantitys[0];
      }
      this.$Request.post(url, data, header + sessionid).then(res => {

        if (res.code == 200) {

          let obj = {
            appId: res.data.WX.appId,
            nonceStr: res.data.WX.nonceStr,
            package: res.data.WX.package, // 固定值，以微信支付文档为主
            partnerid: res.data.WX.partnerid,
            prepayid: res.data.WX.prepayid,
            timeStamp: res.data.WX.timeStamp,
            sign: res.data.WX.sign, // 根据签名算法生成签名
          }


          // 第一种写法，传对象
          let orderInfo = obj;
          // 第二种写法，传对象字符串
          //let orderInfo = JSON.stringify(obj);
          console.log(orderInfo);

          uni.requestPayment({
            // provider: 'wxpay',
            // timeStamp: orderInfo.timestamp,
            // nonceStr: orderInfo.noncestr,
            // package: 'prepay_id='+orderInfo.prepayid,
            // signType: 'MD5',
            // paySign: orderInfo.sign,

            //appId:orderInfo.appId,
            timeStamp: orderInfo.timeStamp,
            nonceStr: orderInfo.nonceStr,
            package: orderInfo.package,
            signType: 'MD5',
            paySign: orderInfo.sign,
            //total_fee: 10,
            success: function (res) {
              console.log('success:' + JSON.stringify(res));
            },
            fail: function (err) {
              console.log('fail:' + JSON.stringify(err));
            },
            complete: function (res) {
              console.log('支付完成' + JSON.stringify(res));
              var url = '/pay/success/success';
              console.log('get url', url)
              if (res.errMsg == 'requestPayment:ok') {
                wx.showModal({
                  title: '提示',
                  content: '付款成功'
                });
                if (url) {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages' + url
                    });
                  }, 2000)
                } else {
                  setTimeout(() => {
                    wx.navigateBack()
                  }, 2000)
                }
              }
              return;
            }
          });


        } else {
          uni.showToast({title: res.message, icon: "none"});
        }
      })
      // setTimeout(()=>{
      // 	uni.setStorage({
      // 		key:'paymentOrder',
      // 		data:paymentOrder,
      // 		success: () => {
      // 			uni.hideLoading();
      // 			uni.redirectTo({
      // 				url:"../pay/payment/payment?amount="+this.sumPrice
      // 			})
      // 		}
      // 	})
      // },1000)

    },
    //选择收货地址
    selectAddress() {
      uni.navigateTo({
        url: '../user/address/address?type=select'
      })
    }
  }
}
</script>

<style lang="scss">
@import "./confirmation";
</style>
